package sms

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"gitchina/kly_service/util"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
)

var client *http.Client
var smsUserId, smsPwd, smsUrl, smsTemplate string

type MongateApi struct {
	phone string
	text  string
}

type SendSmsRS struct {
	XMLName xml.Name `xml:"string"`
	Code    string   `xml:",chardata"`
}

func init() {
	client = &http.Client{}
	smsUserId = beego.AppConfig.String("smsUseId")
	smsPwd = beego.AppConfig.String("smsPwd")
	smsUrl = beego.AppConfig.String("smsUrl")
	smsTemplate = beego.AppConfig.String("smsTemplate")
}

func (m *MongateApi) Send() {
	var err error
	var resp *http.Response
	var body []byte
	text := fmt.Sprintf(smsTemplate, smsUserId, smsPwd, m.phone, m.text)
	reader := bytes.NewBuffer([]byte(text))
	req, err := http.NewRequest("POST", smsUrl, reader)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.ContentLength = int64(reader.Len())
	resp, err = client.Do(req)
	if resp != nil {
		defer resp.Body.Close()
	}
	if err == nil {
		if body, err = ioutil.ReadAll(resp.Body); err == nil {
			var rs SendSmsRS
			if err = xml.Unmarshal(body, &rs); err == nil {
				if len(rs.Code) < 7 {
					err = fmt.Errorf("invalid response code:%s", rs.Code)
				}
			}
		}
	}
	if err != nil {
		util.GetLogger().Error("[util-sms] - error:%s", err.Error())
	}
}
